//
//  CQReleaseViewController.swift
//  swift-weibo
//
//  Created by 陈乾 on 15/11/3.
//  Copyright © 2015年 陈乾. All rights reserved.
//

import UIKit
import SVProgressHUD

class CQReleaseViewController: UIViewController {
    
    //MARK: - 属性
    
    ///微博内容的最大长度
    
   private let labelMaxLength = 20
    
    ///toolBar底部的约束
    var toolBarBottomConstraint :NSLayoutConstraint?
    //MARK: -viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置颜色
        self.view.backgroundColor = UIColor(white: 0.8, alpha: 1)
        //准备UI
        prepareUI()
        //监听键盘弹出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //一进来就弹出键盘 这里的效果 有点点不好 最好放到 viewDidAppear
//        textView.becomeFirstResponder()
        
    }
    
    //MARK: - viewDidAppear
    override func viewDidAppear(animated: Bool) {
         textView.becomeFirstResponder()
    }
    
    //MARK: -准备UI
    func prepareUI()
    {
        //设置导航条
        setNavigationVC()
        //设置工具条
        setToolBar()
        //设置编辑view
        setUpTextView()
        
        ///准备内容大小的label
        prepareLabel()
        
    }
    
    
    //MARK: -准备label
    func prepareLabel() {
       
        //添加到控制器的view
        view.addSubview(lengthTipLabel)
        //添加约束
        lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
        
    }
    
    //MARK: -//设置导航条
    private func setNavigationVC()
    {
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        //禁止点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        //中间的view
        
        
        
        let str = "发微博"
        let name = CQUserAccount.loadAccount()?.name
        let title = str + "\n" + name!
        ///创建 可变的属性文本
        let textAttr = NSMutableAttributedString(string: title)
        
        let lable = UILabel()
        
        //label的字体大小
        lable.font = UIFont.systemFontOfSize(14)
        lable.textColor = UIColor.lightGrayColor()
        lable.numberOfLines = 0
        lable.textAlignment = NSTextAlignment.Center
        
        //截取名字
        let range = (title as NSString).rangeOfString(name!)
        
        textAttr.addAttribute(NSForegroundColorAttributeName, value: UIColor.purpleColor(), range: range)
        textAttr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        
        
        //赋值给label
        lable.attributedText = textAttr
        //设置大小
        lable.sizeToFit()
        navigationItem.titleView = lable
        
        
        
    }
    //MARK: - 设置工具条
    private func setToolBar() {
        //添加子控件到view
        view.addSubview(toolBar)
        //添加约束
      let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.screenWidth(), height: 44))
      toolBarBottomConstraint = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        var imageActionArr = [
            
            ["imageName": "compose_toolbar_picture", "action": "toolbar"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]
        ]
        
        //创建一个数组用来装UIBarButtonItem
        var itemArr = [UIBarButtonItem]()
        
        //遍历数组 拿出字典
        for dic in imageActionArr {
            //取出图片名称
            let name = dic["imageName"]
            //取出事件名字
            let functionName = dic["action"]
            //创建Item
            let item = UIBarButtonItem(imageName: name!)
            
            //item不能添加事件  需要取出被包装的button
            let button = item.customView as? UIButton ?? nil
            //添加点击事件
            button!.addTarget(self, action: Selector(functionName!), forControlEvents: UIControlEvents.TouchUpInside)
            
            //把item装进去
            itemArr.append(item)
            
            //添加弹簧
            
            itemArr.append( UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            
        }
        
        //移除最后一个多余的弹簧
        itemArr.removeLast()
        
        //把items添加到
        toolBar.items = itemArr
        
    }
    
    //MARK: - 设置编辑view 使用自定义的UITextView
    private func setUpTextView() {
        //添加都父view
      view.addSubview(textView)
       //设置约束
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
       //设置偏移
        textView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
        //垂直弹簧效果
        textView.alwaysBounceVertical = true
        //拖拽 消失键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        //设置代理
        textView.delegate = self
        
       
        
    }
    /*
    userInfo = {
    UIKeyboardAnimationCurveUserInfoKey = 7;
    UIKeyboardAnimationDurationUserInfoKey = "0.25";
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
    UIKeyboardIsLocalUserInfoKey = 1;
    }}

    */
    
    //MARK: - 通知回调
    func willChangeFrame(notifacation: NSNotification) {
     //动画时间
    let duration = notifacation.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as? NSTimeInterval
    //键盘完全出来的时候的frame
    let endFrame = notifacation.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
    
    //重新设置底部toolBar的底部约束
        toolBarBottomConstraint?.constant = -(UIScreen.screenHeight() - endFrame.origin.y)
    
      //动画 重新布局
        UIView.animateWithDuration(duration!) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    
    
    //MARK: -按钮点击事件
    // @objc private 要加上 否者底层的oc 不知道怎么调
    
    ///图片按钮
    @objc private func toolbar() {
        
        print("点击图片")
    }
    ///图片#
    func trend() {
        
        print("点击#")
        
    }
     ///点击@
    func mention() {
        
        print("点击@")
        
    }
    ///点击表情
    func emoticon() {
        
        //选择键盘
        switchKeyboard()
        
    }
    ///点击加号
    func add() {
        
        print("点击加号")
        
    }
    
    //MARK: - 选中普通键盘还是表情键盘
    func switchKeyboard() {
        
        //取消第一响应者
        textView.resignFirstResponder()
        
 
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            
            //如果返回的nil 就是系统的键盘 否者返回我们的键盘
            self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
            
            //成为第一响应者
       self.textView.becomeFirstResponder()
        })
        
    }
    
    
    //MARK: - 导航条按钮点击事件
    ///取消
    func dismiss() {
        
        SVProgressHUD.dismiss()
        //返回控制器
        dismissViewControllerAnimated(true, completion: nil)
        //键盘消失 取消第一响应者
        textView.resignFirstResponder()
    }
    ///发送微博
    func sendStatus() {
        //获取要发送的微博字符串
       let status = textView.geteEmoticonText()
        
        let currentLength = status.characters.count
       //如果超过限定的长度就禁止发送
        if labelMaxLength - currentLength < 0 {
        
            //提示
            SVProgressHUD.showErrorWithStatus("超过长度发送失败", maskType: SVProgressHUDMaskType.Black)
           return
        }
        
        
    SVProgressHUD.showWithStatus("正在发布微博..", maskType: SVProgressHUDMaskType.Black)
        
        CQNetworkTool.shareInstance.sendStatus(status) { (result, error) -> () in
            if error != nil {
             
                SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Gradient)
             
            }
            
            //来这里说明发送成功
            
            self.dismiss()
            
            
        }
        
    }
    
    //MARK: - 懒加载
    ///toolBar
    private lazy var toolBar: UIToolbar = {
        
        let toolb = UIToolbar()
        
        
        return toolb
        }()
    ///编辑的view
    private lazy var textView: CQPlaceHoldTextView = {
        
        let tv = CQPlaceHoldTextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.backgroundColor = UIColor.cyanColor()
        tv.placeHold = "分享新鲜的微博..."
         
        return tv
    }()
    
    ///表情控制器
    lazy var emoticonVC: CQEmoticonController = {
        let vc = CQEmoticonController()
         //??
         self.addChildViewController(vc)
         vc.textView = self.textView
        
        
        return vc
        }()
    ///发布数量的label
    lazy var lengthTipLabel: UILabel = {
        let label = UILabel(fontSize: 12, color: UIColor.lightGrayColor())
        
        //设置默认的长度
        label.text = String(self.labelMaxLength)
        
        return label
        }()
    
    
    
/*end*/
}

extension CQReleaseViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        
        //当文本发生改变 会来这个方法  我们就来计算 label的内容
        
        //获得当前文本的长度
        let currentLength = textView.geteEmoticonText().characters.count
        
        //剩余长度
        let length = labelMaxLength - currentLength
        
        //显示剩余的内容
        lengthTipLabel.text = String(length)
        
        //文字变色
        lengthTipLabel.textColor = length > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
        
        
        
    }
    
}


